<template>
  <div>
    <SearchContainer is-width @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex justify-between" :model="formState">
        <div class="flex">
          <a-form-item name="wardName" label="" class="w-56">
            <SelectArea v-model:value="formState.bqbh" use-cache @select="getData()" />
          </a-form-item>
          <a-form-item name="stdate" label="发药日期" class="w-72 ml-2">
            <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item name="zjm" label="" class="w-60 ml-2">
            <a-input v-model:value="formState.pyjm" placeholder="床位号/姓名/助记码/住院号" />
          </a-form-item>
          <a-form-item name="ypzjm" label="" class="w-60 ml-2">
            <a-input v-model:value="formState.ypzjm" placeholder="药品名称/助记码" />
          </a-form-item>
        </div>
        <div class="flex">
          <SelectDrugRoom
            v-model:value="formState.drugStoreId"
            placeholder="选择药房"
            select-first
            :params="{ isProducer: '1' }"
            class="w-60 mb-2 mr-4"
            @select="onSelectDrugRoom"
          />
          <a-form-item class="w-60" label="审核人">
            <a-select v-model:value="formState.shr" :options="pharmacistSelectData" allow-clear placeholder="请选择" @change="setLocalStorageEvent" />
          </a-form-item>
        </div>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex justify-end items-center pb-2">
        <BaseButton type="primary" ghost @click="onPrint"> <BaseIcon name="PrinterOutlined" :loading="printLoading" /> 退药单</BaseButton>
      </div>
      <BaseTable column-code="00001036" :loading="loading" :data-source="tableData" fill bordered :pagination="pagination">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'yzzxlb'">
            <a-tag v-if="record.yzzxlb == 0" color="blue">全部</a-tag>
            <a-tag v-else-if="record.yzzxlb == 1" color="blue  ">临时</a-tag>
            <a-tag v-else-if="record.yzzxlb == 2" color="blue">长期</a-tag>
          </template>
          <template v-if="column.dataIndex === 'brName'">
            <span>{{ record.brName }}</span>
            <span class="ml-4">{{ record.brXb }}</span>
            <span class="ml-4">{{ record.brAge }}</span>
          </template>
          <template v-if="column.dataIndex === 'sfpj'">
            <a-tag v-if="record.sfpj == 0" color="blue">针剂</a-tag>
            <a-tag v-else-if="record.sfpj == 1" color="success">片剂</a-tag>
          </template>
          <template v-if="column.dataIndex === 'advName'">
            <MedicineInfo
              :value="{
                mc: record?.advName,
                cj: record?.cj,
                jl: record?.clinicalDose + record?.clinicalDoseUnit,
                yf: record?.deliverRoute?.yffl,
                pl: record?.fqy?.pl,
                gg: record?.spc
              }"
            />
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <BaseButton :confirm-text="record.sffzyz ? '当前药品为父子医嘱，需一起退药' : '确定退药？'" type="link" size="small" @click="onReturn(record)">
              退药
            </BaseButton>
          </template>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'

const { empId } = useUserStore()
const printLoading = ref(false)

const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  ward: ''
})
const pharmacistSelectData = ref([])
const { loading, tableData, getData, pagination } = useTable({
  url: '/inp/zyyf/getDistributeDrugList',
  immediate: false,
  formatParams: () => {
    return {
      wardId: formState.value.bqbh,
      chkZJ: '0',
      eddate: formState.value['dateRange']?.[1],
      stdate: formState.value['dateRange']?.[0],
      yjlx: '2',
      zjm: formState.value.pyjm,
      auditEmpId: formState.value.shr,
      ...formState.value,
      shr: undefined
    }
  }
})
//获取审核人下拉（类别为药剂师）
const getSelectPharmacist = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '5',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999,
    notEmpIdList: [empId] // 当前登录但id
  })
  if (code !== 0) return
  pharmacistSelectData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
  const reviewerValue = JSON.parse(window.localStorage.getItem('dispensingReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    const flag = pharmacistSelectData.value.some((item) => item.value === reviewerValue.value)
    //保存24小时
    if (dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') >= 0 && dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') < 24 && flag) {
      formState.value.shr = reviewerValue.value
    }
  }
}

const onReturn = async (record) => {
  // if (!formStates.value?.drugStoreId) return message.error('请选择发药药房')
  if (!formState.value?.shr) return message.error('请选择审核人')
  const res = await post('/inp/zyyf/doRefundDrug', {
    inpAdviceExecId: record.inpAdviceExecId,
    shr: formState.value?.shr
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg)
  getData()
}
const onSelectDrugRoom = (val) => {
  formState.value.drugStoreId = val.id
  window.localStorage.setItem(
    'dispensingDrugStoreId',
    JSON.stringify({
      value: formState.value.drugStoreId
    })
  )
}
const setLocalStorageEvent = () => {
  window.localStorage.setItem(
    'dispensingReviewer',
    JSON.stringify({
      time: dayjs().format(),
      value: formState.value.shr
    })
  )
}
// 打印退药单
const onPrint = async () => {
  printLoading.value = true
  const res = await post('/inp/Print/printBeforeTYD', {
    wardId: formState.value.bqbh,
    chkZJ: '0',
    eddate: formState.value['dateRange']?.[1],
    stdate: formState.value['dateRange']?.[0],
    yjlx: '2',
    zjm: formState.value.pyjm,
    auditEmpId: formState.value.shr,
    ...formState.value,
    shr: undefined
  })
  printLoading.value = false
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  window.openExe?.rpt(res.data) //调用winform打印
}
onMounted(() => {
  getSelectPharmacist()
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingDrugStoreId'))
  if (drugStoreIdValue && drugStoreIdValue.value) {
    formState.value.drugStoreId = drugStoreIdValue.value
  }
  getData()
})
</script>
<style scoped>
.dislay {
  height: 55px;
  padding: 0 20px;
  background: #f5f7fb;
}
</style>
